<?php 
namespace app\wework\controller\user\staff;

use think\facade\Db;
use app\wework\controller\Base;
use app\wework\model\BaseModel;
use app\wework\model\user\staff\StaffModel;
use app\wework\model\QyWechatApi;
use think\facade\Session;
use think\facade\Queue;

use think\facade\Log;
/**
* 企业成员
**/
class Staff extends Base {
  /**
  * 弹框选择成员
  * @param name  部门名
  * @return \think\Response
  */
  public function pop()
  {   
      $res = [];
      $id = $this->req->param('id',0); //部门id, 默认0,最顶级部门
      if($id == 0){
        $res['staff'] = [];
        $res['department'] = BaseModel::getAll('kt_wework_department',['wid'=>$this->wid,'department_parentid'=>$id],false,'department_id as id,department_name as name');
        foreach ($res['department'] as $k => $v) {
            $res['department'][$k]['haschildren'] = true;
            $res['department'][$k]['children'] = $this->popInfo($v['id']);
        }
      }else{
        $res = $this->popInfo($id);
      }
     
      return success('弹框成员数据',$res);
  }

     public function department(){
          $department_name = $this->req->param("department_name");
          $department_id = $this->req->param("department_id");
          $res = StaffModel::department($department_id,$department_name);
          
          return success('部门数据',$res);
     }
  /**
  * 弹框选择成员 没有做部门限制，忽略部门查询
  * @param name  部门名
  * @return \think\Response
  */
  public function popInfo($id)
  {
      $data = [];
      //成员数据
      $data['staff'] = BaseModel::getAll('kt_wework_staff',[['wid', '=' ,$this->wid],['status','=',1],['is_del','=',0]],"JSON_CONTAINS(department,'{$id}','$')",'id,name');  //获取数据
      $where = [];
      $where[] = ['wid', '=' ,$this->wid];
      $where[] = ['department_parentid', '=' ,$id];
      $field = 'department_id as id,department_name as name';    //获取字段数据, 数组|字符串

      $data['department'] = BaseModel::getAll('kt_wework_department',$where,'',$field);  //获取数据
      foreach ($data['department'] as &$department) {
          $department['haschildren'] = BaseModel::count('kt_wework_department',[['wid','=',$this->wid],['department_parentid','=',$department['id']]]) > 0 || BaseModel::getAll('kt_wework_staff',[['wid', '=' ,$this->wid],['status','=',1],['is_del','=',0]],"JSON_CONTAINS(department,'".$department['id']."','$')",'id,name') > 0 ? true : false;
      }
      return $data;
  }

  /**
  * 成员列表
  * @param page 页码
  * @param size 每页条数
  * @param name 成员名
  * @param departmentid 所在部门id, 不填默认全部
  * @return \think\Response
  */
     public function index(){
          $wid = Session::get('wid');
          $page = $this->req->param('page',1); 
          $size = $this->req->param('size',10);
          $department = $this->req->param('departmentid',0);
          $where = [];
          $where[] = ['s.wid','=', $wid];  //账户id
          $name = $this->req->param('name','');  //模糊查询 成员名
          if($name) $where[] = ['s.name','like','%'.$name.'%'];
          $whereRaw = "";
          // if($department) {
          //      $department = StaffModel::departments($department);
          //     if($department) for ($i=0;$i<count($department);$i+=1){$whereRaw .= "JSON_CONTAINS(s.department, '{$department[$i]}', '$') or ";}
          //     $whereRaw = substr($whereRaw, 0,-3);
          // }
          $data = StaffModel::list($where,$department,$page);  //获取数据  
          return success('成员列表',$data);
    }

    /**
     * 成员详情基本数据
     * @param  staffId 成员主键id
     * @return \think\Response
     */
  public function detail()
    {
      $wid = Session::get('wid');
      $staffId = $this->req->param('staffId');
      if(!$staffId) return error("缺少参数");
      $staff = StaffModel::detail($staffId);

      $startTime = strtotime(date('Y-m-d',strtotime("-1 day")));
      $endTime = time();
      $behaviorData = StaffModel::behaviorData($staffId,[],$startTime,$endTime);
      $staff['behaviorData'] = [];
      if($behaviorData)$staff['behaviorData'] = $behaviorData[0];
      return success('成员详情',$staff);
    }

     /**
     * 成员统计数据
     * @param  staffId 成员主键id
     * @return \think\Response
     */
  public function statistics()
    {
      $wid = Session::get('wid');
      $staffId = $this->req->param('staffId');
      $dateType = $this->req->param('dateType','week');
      $startTime = 0;
      $endTime = 0;
      switch ($dateType) {
        case 'day':  //昨天数据
          $startTime = strtotime(date('Y-m-d'));
          $endTime = time();
          break;
        case 'week':  //一周数据
          $startTime = date('Y-m-d',strtotime("-7 day"));//前一周
          $endTime = date('Y-m-d',strtotime("-1 day"));//昨天
          break;
        case 'mouth':  //一月数据
          $startTime = date('Y-m-d',strtotime("-30 day"));//前一月
          $endTime = date('Y-m-d',strtotime("-1 day"));//昨天
          break;
        case 'self':  //自定义
          $selfTime = $this->req->param('self_time/a');
          if(!$selfTime) return error('请选择日期');
          $startTime = strtotime($selfTime[0]);
          if($startTime < strtotime("-180 day")) return error('最多查看180天内的数据');
          $endTime = strtotime($selfTime[1]);
          if($startTime - $endTime > 30*24*3600) return error('支持的最大查询跨度为30天');
          break;
      }
      $behaviorData = StaffModel::behaviorData($staffId,[],$startTime,$endTime);
      $behaviorData = empty($behaviorData) ?: array_map(function($i){$i['stat_time']=date("Y-m-d",$i['stat_time']);return $i;}, $behaviorData); 
      return success('成员列表',$behaviorData);
    }

     /**
          * 同步成员列表
          * @param departmentid 所在部门id, 不填默认全部
          * @return \think\Response
     */
     public function sync(){
          $wid = Session::get('wid');
          $config = BaseModel::find('kt_wework_selfapp',['wid'=>$wid],'agent_id');
          if(!$config) return error('请先设置通讯录配置');
          $departmentRes = QyWechatApi::getDepartmentList();
          $mh = curl_multi_init();
          $url = $this->req->domain()."/wework/user/staff/users";
          $conn = [];
          if($departmentRes['errcode'] == 0){
               $departmentList = $departmentRes['department'];
               if(!$departmentList)return error("请配置自建应用可见范围");
               StaffModel::updateDepart($departmentList);
               $departmentId = array_column($departmentList, 'id');
               $url = $this->req->domain()."/wework/user/staff/users";
               $mh = curl_multi_init();
               for ($i=0;$i<count($departmentId);$i++) {
                    $data = http_build_query(["id"=>$departmentId[$i],"wid"=>$wid]);
                    $conn[$i]=curl_init($url);
                    curl_setopt($conn[$i],CURLOPT_RETURNTRANSFER,1); //如果成功只将结果返回，不自动输出任何内容
                    curl_setopt($conn[$i],CURLOPT_TIMEOUT,0);
                    curl_setopt($conn[$i], CURLOPT_POSTFIELDS, $data); //post 传参
                    curl_multi_add_handle ($mh,$conn[$i]);
               }
               do { $n=curl_multi_exec($mh,$active); }
               while ($active);
               $result = true;
               for ($i=0;$i<count($departmentId);$i++) {
                    $res[$i]=curl_multi_getcontent($conn[$i]);
                    curl_close($conn[$i]);
                    if($res[$i] != 1){
                         $result = false;
                    }
               }
          }
          return success('同步成功');
    }
    
     public function users(){
          $data = $_POST;
          $qyuserInfos = QyWechatApi::getStaffList($data["id"],$data["wid"]);
          foreach ($qyuserInfos["userlist"] as $value) {
              $send = QyWechatApi::send_textcard($value["userid"],$data["wid"],"通讯录同步请求","请点击该链接同步后台员工信息，请选择全部选项，并确认提交，否则将永久性获取不到详细数据",$this->req->domain().'/wework/h5.CustomerPortrait/staff.html?wid='.$data["wid"]);
              Log::error(json_encode($send,320));
          }
          return "1";
     }

}

